package com.example.handsets8app.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.handsets8app.Base.BaseActivity;
import com.example.handsets8app.Base.BaseConfig;
import com.example.handsets8app.Bean.JJHLoginBean;
import com.example.handsets8app.Bean.JJHLoginResult;
import com.example.handsets8app.R;
import com.example.handsets8app.RetrufitHelp.BaseSubscriber;
import com.example.handsets8app.RetrufitHelp.ExceptionHandle;
import com.example.handsets8app.RetrufitHelp.RetrofitClient;
import com.example.handsets8app.Sever.RefreshTokenService;
import com.example.handsets8app.Utils.GetDeviceId;
import com.example.handsets8app.Utils.SPUtil;
import com.example.handsets8app.Utils.StringUtil;
import com.example.handsets8app.Utils.ThreadManager;
import com.example.handsets8app.Utils.ToastUtil;

public class LoginActivity extends BaseActivity {

    private TextView setIp;
    private EditText getAccount;
    private EditText getPassWord;
    private Button btLoging;
    private String account;
    private String password;
    private String DeviceId;
    private JJHLoginBean jjhLoginBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getPermissions();
    }

    @Override
    public int initLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {

        setIp = (TextView) findViewById(R.id.tv_set_ip);
        setIp.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        getAccount = (EditText) findViewById(R.id.et_account);
        getPassWord = (EditText) findViewById(R.id.et_password);
        btLoging = (Button) findViewById(R.id.bt_login);

        getAccount.setText((String) SPUtil.get(LoginActivity.this, BaseConfig.NAME, ""));
        getPassWord.setText((String) SPUtil.get(LoginActivity.this, BaseConfig.PASS, ""));


        //获取设备唯一标识
        ThreadManager.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    DeviceId = GetDeviceId.getDeviceId(LoginActivity.this);
                    //获取保存在sd中的 设备唯一标识符
                    String readDeviceID = GetDeviceId.readDeviceID(LoginActivity.this);
                    //获取缓存在  sharepreference 里面的 设备唯一标识
                    String string = (String) SPUtil.get(LoginActivity.this, BaseConfig.Device_id, "");
                    //判断 app 内部是否已经缓存,  若已经缓存则使用app 缓存的 设备id
                    if (string != null && !string.equals("")) {
                        // 说明有保存，那么久将其放出去呗
                        if (readDeviceID.equals(string)) {
                            //缓存和文件地址一样，直接返回出去
                            DeviceId = readDeviceID;
                        }
                    } else {
                        DeviceId = GetDeviceId.getDeviceId(LoginActivity.this);
                        GetDeviceId.saveDeviceID(DeviceId, LoginActivity.this);
                    }
                    //最后再次更新app 的缓存
                    SPUtil.put(LoginActivity.this, BaseConfig.Device_id, DeviceId);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //这里 可以 去做  获取到 设备id 后的 操作
//                            jjhLoginBean.setTerminalComputerCpuId(DeviceId);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void initData() {

        //点击设置地址
        setIp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转页面 进行地址设置
                iosLoadDialog.show();
                startActivity(new Intent(LoginActivity.this, SettingIPActivity.class));
                iosLoadDialog.dismiss();
            }
        });


        btLoging.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                account = getAccount.getText().toString().trim();
                password = getPassWord.getText().toString().trim();

                if (StringUtil.isNullOrEmpty(account)) {
                    ToastUtil.showToast("用户名为空，请输入用户名");
                    return;
                }

                if (StringUtil.isNullOrEmpty(password)) {
                    ToastUtil.showToast("密码为空，请输入用户名");
                    return;
                }

                //如果密码，和用户名都不为空，那么就去请求
                iosLoadDialog.show();

                checkAccountAndPassword(account, password);
            }
        });
    }

    private void checkAccountAndPassword(final String account, final String password) {
        jjhLoginBean = new JJHLoginBean(account, password, "1", DeviceId);
        RetrofitClient.getInstance(LoginActivity.this, BaseUrl).JJHLogin(jjhLoginBean, new BaseSubscriber<JJHLoginResult>(LoginActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                iosLoadDialog.dismiss();
                ToastUtil.showToast(e.message);
            }

            @Override
            public void onNext(JJHLoginResult jjhLoginResult) {
                //返回数据正常，进行正常解析
                if (jjhLoginResult.getCode().equals("200")) {
                    //返回数据是200 登录成功，进行页面跳转，以及正常数据保存
                    iosLoadDialog.dismiss();

                    //新中新    新的  手持机检票
                    startActivity(new Intent(LoginActivity.this, WelcomRzScienceActivity.class));

                    SPUtil.put(LoginActivity.this,  BaseConfig.NAME, account);
                    SPUtil.put(LoginActivity.this, BaseConfig.PASS, password);
                    // 保存 token 后期接口 调用
                    SPUtil.put(LoginActivity.this,  BaseConfig.JJH_TOKEN, jjhLoginResult.getData().getUserInfo().getAccessToken());
                    SPUtil.put(LoginActivity.this, BaseConfig.JJH_TOKEN_REFSH, jjhLoginResult.getData().getUserInfo().getRefreshToken());

                    SPUtil.put(LoginActivity.this,  BaseConfig.JJH_CHECK_LOGIN_APP, true);
                    headers.put("Token", jjhLoginResult.getData().getUserInfo().getAccessToken());

                    // 启动服务， 去更新 token
                    startService(new Intent(LoginActivity.this, RefreshTokenService.class));
                    finish();
                } else {
                    //对失败进行反馈
                    ToastUtil.showToast(jjhLoginResult.getMessage());
                    iosLoadDialog.dismiss();
                }
            }
        });
    }


    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //表示未授权时
                //进行授权
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {

            }
        }
    }

    /**
     * 权限申请返回结果
     *
     * @param requestCode  请求码
     * @param permissions  权限数组
     * @param grantResults 申请结果数组，里面都是int类型的数
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                // grantResults.length > 0&& grantResults[0] == PackageManager.PERMISSION_GRANTED
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) { //同意权限申请
                    // Toast.makeText(this,"同意权限申请",Toast.LENGTH_SHORT).show();
                    ToastUtil.showToast("同意权限申请");
                } else { //拒绝权限申请
                    //Toast.makeText(this,"权限被拒绝了",Toast.LENGTH_SHORT).show();
                    ToastUtil.showToast("权限被拒绝了");
                }
                break;
            default:
                break;
        }
    }


}
